package org.tinygame.herostory.login;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinygame.herostory.MySqlSessionFactory;
import org.tinygame.herostory.async.AsyncOperationProcessor;
import org.tinygame.herostory.async.IAsyncOperation;
import org.tinygame.herostory.login.db.IUserDao;
import org.tinygame.herostory.login.db.UserEntity;
import org.tinygame.herostory.util.RedisUtil;
import redis.clients.jedis.Jedis;

import java.util.function.Function;

/**
 * @author shkstart
 * @create 2022-05-07 15:49
 */
public class LoginService {
    private static final Logger LOGGER= LoggerFactory.getLogger(LoginService.class);
    /**
     * 单例对象
     */
    private static final LoginService _instance=new LoginService();
    /**
     * 私有化默认构造器
     */
    private LoginService(){

    }

    public static LoginService getInstance(){

        return _instance;
    }

    /**
     * 用户登录
     * @param username 用户名称
     * @param passWord 密码
     * @param callback 回调函数
     * @return 用户实体
     */
    public void userLogin(String username, String passWord, Function<UserEntity,Void> callback){
        if(null==username||null==passWord){
            return;
        }

        IAsyncOperation asyncOp=new AsyncGetUserByName(username,passWord) {
            @Override
            public void doFinish(){
                if(null!=callback){
                    callback.apply(this.getUserEntity());
                }
            }
        };

        //与数据库交互的部分在doAsync执行完成后
        //回到主线程，执行doFinish
        AsyncOperationProcessor.getInstance().process(asyncOp);

    }

    /**
     * 更新redis用户基本信息
     * @param userEntity 用户实体
     */
    private void updateUserBasicInfoInRedis(UserEntity userEntity){
        if(null==userEntity){
            return;
        }
        try(Jedis redis= RedisUtil.getRedis()){
            //获取用户id
            int userId=userEntity.userId;

            JSONObject jsonObj=new JSONObject();
            jsonObj.put("userId",userId);
            jsonObj.put("userName",userEntity.userName);
            jsonObj.put("heroAvatar",userEntity.heroAvatar);

            //更新redis数据
            redis.hset("User_"+userId,"BasicInfo", jsonObj.toJSONString());
        }catch (Exception ex){
            LOGGER.error(ex.getMessage(),ex);
        }
    }

    /**
     * 内部类：异步方式获取用户
     */
    private class AsyncGetUserByName implements IAsyncOperation{
        /**
         * 用户名称
         */
        private final String _userName;
        /**
         * 用户密码
         */

        private final String _password;

        /**
         * 用户实体
         */
        private UserEntity _userEntity=null;

        /**
         * 构造器
         * @param userName 用户名称
         * @param password 用户密码
         */
        AsyncGetUserByName(String userName,String password){
            _userName=userName;
            _password=password;
        }

        /**
         * 获取用户实体
         * @return 用户实体
         */
        public UserEntity getUserEntity(){
            return _userEntity;
        }

        @Override
        public int bindId() {
            return _userName.charAt(_userName.length()-1);
        }

        @Override
        public void doAsync() {
            //try with,执行完后自动调用close
            try(SqlSession mySqlSession = MySqlSessionFactory.openSession()) {
                //获取DAO
                IUserDao dao=mySqlSession.getMapper(IUserDao.class);

                LOGGER.info("当前线程={}",Thread.currentThread().getName());

                //获取用户实体
                UserEntity userEntity = dao.getUserByName(_userName);

                if(null!=userEntity){
                    if(!_password.equals(userEntity.password)){
                        LOGGER.error("用户密码错误，userName={}",_userName);
                    }
                }else{
                    //新建用户实体
                    userEntity=new UserEntity();
                    userEntity.userName=_userName;
                    userEntity.password=_password;
                    userEntity.heroAvatar="Hero_Shaman";
                    //这里userEntity并无userId值
                    //System.out.println("*********"+userEntity.userId);
                    //将新用户插入数据库，通过selectKey为userEntity.userId自动赋值（自增id）
                    dao.insertInto(userEntity);
                    //这里userEntity有userId值
                    //System.out.println("*********"+userEntity.userId);
                }

                _userEntity=userEntity;

                LoginService.getInstance().updateUserBasicInfoInRedis(userEntity);

            } catch (Exception ex) {
                LOGGER.error(ex.getMessage(),ex);
            }
        }
    }
}
